#include "dap_usb_handle.h"
#include "DAP.h"
#include "usbd_core.h"
#include "freertos/event_groups.h"
#include "freertos/ringbuf.h"
#include "usb_public.h"
#include "esp_log.h"
#include "usb2uart.h"
#include "swo.h"
#include "work_status_setting.h"

static const char *TAG = "dap_usb_handle";

DAP_usb_config_t g_dap_usb_config;
extern volatile int dap_respond;
#define DAP_USB_SEND_TASK_AFFINITY 1
#define CDC_ACM_TASK_AFFINITY      1

#define USB_CONFIG_SIZE (9 + CMSIS_DAP_INTERFACE_SIZE + CDC_ACM_DESCRIPTOR_LEN + CONFIG_MSC_DESCRIPTOR_LEN)
#define INTF_NUM        (2 + 1 + CONFIG_MSC_INTF_NUM)

/**********************************dap-link usb描述符*******************************************/
__ALIGN_BEGIN const uint8_t USBD_WinUSBDescriptorSetDescriptor[] = {
    WBVAL(WINUSB_DESCRIPTOR_SET_HEADER_SIZE), /* wLength */
    WBVAL(WINUSB_SET_HEADER_DESCRIPTOR_TYPE), /* wDescriptorType */
    0x00, 0x00, 0x03, 0x06, /* >= Win 8.1 */  /* dwWindowsVersion*/
    WBVAL(USBD_WINUSB_DESC_SET_LEN),          /* wDescriptorSetTotalLength */
#if (USBD_WEBUSB_ENABLE)
    WBVAL(WINUSB_FUNCTION_SUBSET_HEADER_SIZE), // wLength
    WBVAL(WINUSB_SUBSET_HEADER_FUNCTION_TYPE), // wDescriptorType
    0,                                         // bFirstInterface USBD_WINUSB_IF_NUM
    0,                                         // bReserved
    WBVAL(FUNCTION_SUBSET_LEN),                // wSubsetLength
    WBVAL(WINUSB_FEATURE_COMPATIBLE_ID_SIZE),  // wLength
    WBVAL(WINUSB_FEATURE_COMPATIBLE_ID_TYPE),  // wDescriptorType
    'W', 'I', 'N', 'U', 'S', 'B', 0, 0,        // CompatibleId
    0, 0, 0, 0, 0, 0, 0, 0,                    // SubCompatibleId
    WBVAL(DEVICE_INTERFACE_GUIDS_FEATURE_LEN), // wLength
    WBVAL(WINUSB_FEATURE_REG_PROPERTY_TYPE),   // wDescriptorType
    WBVAL(WINUSB_PROP_DATA_TYPE_REG_MULTI_SZ), // wPropertyDataType
    WBVAL(42),                                 // wPropertyNameLength
    'D', 0, 'e', 0, 'v', 0, 'i', 0, 'c', 0, 'e', 0,
    'I', 0, 'n', 0, 't', 0, 'e', 0, 'r', 0, 'f', 0, 'a', 0, 'c', 0, 'e', 0,
    'G', 0, 'U', 0, 'I', 0, 'D', 0, 's', 0, 0, 0,
    WBVAL(80), // wPropertyDataLength
    '{', 0,
    '9', 0, '2', 0, 'C', 0, 'E', 0, '6', 0, '4', 0, '6', 0, '2', 0, '-', 0,
    '9', 0, 'C', 0, '7', 0, '7', 0, '-', 0,
    '4', 0, '6', 0, 'F', 0, 'E', 0, '-', 0,
    '9', 0, '3', 0, '3', 0, 'B', 0, '-',
    0, '3', 0, '1', 0, 'C', 0, 'B', 0, '9', 0, 'C', 0, '5', 0, 'A', 0, 'A', 0, '3', 0, 'B', 0, '9', 0,
    '}', 0, 0, 0, 0, 0
#endif
#if USBD_BULK_ENABLE
    WBVAL(WINUSB_FUNCTION_SUBSET_HEADER_SIZE), /* wLength */
    WBVAL(WINUSB_SUBSET_HEADER_FUNCTION_TYPE), /* wDescriptorType */
    0,                                         /* bFirstInterface USBD_BULK_IF_NUM*/
    0,                                         /* bReserved */
    WBVAL(FUNCTION_SUBSET_LEN),                /* wSubsetLength */
    WBVAL(WINUSB_FEATURE_COMPATIBLE_ID_SIZE),  /* wLength */
    WBVAL(WINUSB_FEATURE_COMPATIBLE_ID_TYPE),  /* wDescriptorType */
    'W', 'I', 'N', 'U', 'S', 'B', 0, 0,        /* CompatibleId*/
    0, 0, 0, 0, 0, 0, 0, 0,                    /* SubCompatibleId*/
    WBVAL(DEVICE_INTERFACE_GUIDS_FEATURE_LEN), /* wLength */
    WBVAL(WINUSB_FEATURE_REG_PROPERTY_TYPE),   /* wDescriptorType */
    WBVAL(WINUSB_PROP_DATA_TYPE_REG_MULTI_SZ), /* wPropertyDataType */
    WBVAL(42),                                 /* wPropertyNameLength */
    'D', 0, 'e', 0, 'v', 0, 'i', 0, 'c', 0, 'e', 0,
    'I', 0, 'n', 0, 't', 0, 'e', 0, 'r', 0, 'f', 0, 'a', 0, 'c', 0, 'e', 0,
    'G', 0, 'U', 0, 'I', 0, 'D', 0, 's', 0, 0, 0,
    WBVAL(80), /* wPropertyDataLength */
    '{', 0,
    'C', 0, 'D', 0, 'B', 0, '3', 0, 'B', 0, '5', 0, 'A', 0, 'D', 0, '-', 0,
    '2', 0, '9', 0, '3', 0, 'B', 0, '-', 0,
    '4', 0, '6', 0, '6', 0, '3', 0, '-', 0,
    'A', 0, 'A', 0, '3', 0, '6', 0, '-',
    0, '1', 0, 'A', 0, 'A', 0, 'E', 0, '4', 0, '6', 0, '4', 0, '6', 0, '3', 0, '7', 0, '7', 0, '6', 0,
    '}', 0, 0, 0, 0, 0
#endif
};

__ALIGN_BEGIN const uint8_t USBD_BinaryObjectStoreDescriptor[] = {
    0x05,                         /* bLength */
    0x0f,                         /* bDescriptorType */
    WBVAL(USBD_BOS_WTOTALLENGTH), /* wTotalLength */
    USBD_NUM_DEV_CAPABILITIES,    /* bNumDeviceCaps */
#if (USBD_WEBUSB_ENABLE)
    USBD_WEBUSB_DESC_LEN,           /* bLength */
    0x10,                           /* bDescriptorType */
    USB_DEVICE_CAPABILITY_PLATFORM, /* bDevCapabilityType */
    0x00,                           /* bReserved */
    0x38, 0xB6, 0x08, 0x34,         /* PlatformCapabilityUUID */
    0xA9, 0x09, 0xA0, 0x47,
    0x8B, 0xFD, 0xA0, 0x76,
    0x88, 0x15, 0xB6, 0x65,
    WBVAL(0x0100), /* 1.00 */ /* bcdVersion */
    USBD_WINUSB_VENDOR_CODE,  /* bVendorCode */
    0,                        /* iLandingPage */
#endif
#if (USBD_WINUSB_ENABLE)
    USBD_WINUSB_DESC_LEN,           /* bLength */
    0x10,                           /* bDescriptorType */
    USB_DEVICE_CAPABILITY_PLATFORM, /* bDevCapabilityType */
    0x00,                           /* bReserved */
    0xDF, 0x60, 0xDD, 0xD8,         /* PlatformCapabilityUUID */
    0x89, 0x45, 0xC7, 0x4C,
    0x9C, 0xD2, 0x65, 0x9D,
    0x9E, 0x64, 0x8A, 0x9F,
    0x00, 0x00, 0x03, 0x06, /* >= Win 8.1 */ /* dwWindowsVersion*/
    WBVAL(USBD_WINUSB_DESC_SET_LEN),         /* wDescriptorSetTotalLength */
    USBD_WINUSB_VENDOR_CODE,                 /* bVendorCode */
    0,                                       /* bAltEnumCode */
#endif
};

static const uint8_t device_descriptor[] = {
    USB_DEVICE_DESCRIPTOR_INIT(USB_2_1, 0xEF, 0x02, 0x01, USBD_VID, USBD_PID, 0x0100, 0x01),
};

static const uint8_t config_descriptor[] = {
    USB_CONFIG_DESCRIPTOR_INIT(USB_CONFIG_SIZE, INTF_NUM, 0x01, USB_CONFIG_BUS_POWERED, USBD_MAX_POWER),

#if (SWO_STREAM == 1)
    /* Interface 0 */
    USB_INTERFACE_DESCRIPTOR_INIT(0x00, 0x00, 0x03, 0xFF, 0x00, 0x00, 0x02),
    /* Endpoint OUT 2 */
    USB_ENDPOINT_DESCRIPTOR_INIT(DAP_OUT_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
    /* Endpoint IN 1 */
    USB_ENDPOINT_DESCRIPTOR_INIT(DAP_IN_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
    USB_ENDPOINT_DESCRIPTOR_INIT(SWO_IN_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
#else
    /* Interface 0 */
    USB_INTERFACE_DESCRIPTOR_INIT(0x00, 0x00, 0x02, 0xFF, 0x00, 0x00, 0x02),
    /* Endpoint OUT 2 */
    USB_ENDPOINT_DESCRIPTOR_INIT(DAP_OUT_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
    /* Endpoint IN 1 */
    USB_ENDPOINT_DESCRIPTOR_INIT(DAP_IN_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
#endif /*SWO_STREAM*/
       //#ifdef MDLINK_TEST_SPEED
    /* Interface 1 */
    CDC_ACM_DESCRIPTOR_INIT(0x01, CDC_INT_EP, CDC_OUT_EP, CDC_IN_EP, DAP_PACKET_SIZE, 0x00),
//#endif //MDLINK_TEST_SPEED
#ifdef CONFIG_CHERRYDAP_USE_MSC
    MSC_DESCRIPTOR_INIT(MSC_INTF_NUM, MSC_OUT_EP, MSC_IN_EP, DAP_PACKET_SIZE, 0x00),
#endif
};

static const uint8_t other_speed_config_descriptor[] = {
    USB_CONFIG_DESCRIPTOR_INIT(USB_CONFIG_SIZE, INTF_NUM, 0x01, USB_CONFIG_BUS_POWERED, USBD_MAX_POWER),
    /* Interface 0 */
    USB_INTERFACE_DESCRIPTOR_INIT(0x00, 0x00, 0x02, 0xFF, 0x00, 0x00, 0x02),
    /* Endpoint OUT 2 */
    USB_ENDPOINT_DESCRIPTOR_INIT(DAP_OUT_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
    /* Endpoint IN 1 */
    USB_ENDPOINT_DESCRIPTOR_INIT(DAP_IN_EP, USB_ENDPOINT_TYPE_BULK, DAP_PACKET_SIZE, 0x00),
    CDC_ACM_DESCRIPTOR_INIT(0x01, CDC_INT_EP, CDC_OUT_EP, CDC_IN_EP, DAP_PACKET_SIZE, 0x00),
#ifdef CONFIG_CHERRYDAP_USE_MSC
    MSC_DESCRIPTOR_INIT(MSC_INTF_NUM, MSC_OUT_EP, MSC_IN_EP, DAP_PACKET_SIZE, 0x00),
#endif
};

static char *string_descriptors[] = {
    (char[]){ 0x09, 0x04 },             /* Langid */
    "MiDuo",                            /* Manufacturer */
    "Md-Link CMSIS-DAP",                /* Product */
    "00000000000000000123456789ABCDEF", /* Serial Number */
};
static const uint8_t device_quality_descriptor[] = {
    USB_DEVICE_QUALIFIER_DESCRIPTOR_INIT(USB_2_1, 0x00, 0x00, 0x00, 0x01),
};

__WEAK const uint8_t *device_descriptor_callback(uint8_t speed)
{
    (void)speed;
    return device_descriptor;
}

__WEAK const uint8_t *config_descriptor_callback(uint8_t speed)
{
    (void)speed;
    return config_descriptor;
}

__WEAK const uint8_t *device_quality_descriptor_callback(uint8_t speed)
{
    (void)speed;
    return device_quality_descriptor;
}

__WEAK const uint8_t *other_speed_config_descriptor_callback(uint8_t speed)
{
    (void)speed;
    return other_speed_config_descriptor;
}

__WEAK const char *string_descriptor_callback(uint8_t speed, uint8_t index)
{
    (void)speed;

    if (index >= (sizeof(string_descriptors) / sizeof(char *))) {
        return NULL;
    }
    return string_descriptors[index];
}

/**********************************dap-link usb描述符   END   *******************************************/

volatile struct cdc_line_coding g_cdc_lincoding = {
    .dwDTERate = 115200, // 默认波特率 115200
    .bCharFormat = 0,    // 默认 1 位停止位
    .bParityType = 0,    // 默认无校验
    .bDataBits = 8       // 默认 8 数据位
};
//在usb_public统一定义
void usbd_event_handler(uint8_t busid, uint8_t event);

/*  dap-link USB复位事件回调函数 */
void dap_usbd_event_rst(void)
{

}
void dap_usbd_event_cfg(void)
{
    /* 启动两个端点的OUT传输（主机到设备）*/
    usbd_ep_start_read(0, DAP_OUT_EP, (uint8_t *)g_dap_usb_config.dap_buf, DAP_PACKET_SIZE); // 启动DAP端点的数据接收
    usbd_ep_start_read(0, CDC_OUT_EP, g_dap_usb_config.uart_buf, DAP_PACKET_SIZE);           // 启动CDC端点的数据接收
}
/**
 * @brief DAP输出端点回调函数（主机到设备的数据传输完成时调用）
 * @param busid 总线ID（未使用）
 * @param ep 端点号
 * @param nbytes 传输的字节数
 * 
 * 处理从主机接收到的DAP命令：
 * 1. 如果收到中止传输命令，设置中止标志
 * 2. 否则更新请求缓冲区索引和计数器
 * 3. 如果缓冲区未满，启动下一次读取；否则设置空闲标志
 */
void dap_out_callback(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    (void)busid; // 未使用参数
    //ESP_EARLY_LOGI(TAG, "dap_out_callback running...");

    BaseType_t res = xRingbufferSendFromISR(g_dap_usb_config.parent->dap_dataIN_handle,
                                            g_dap_usb_config.dap_buf, nbytes, NULL);
    if (res != pdTRUE) {
        ESP_EARLY_LOGE(TAG, "Cannot write to usb_rcvbuf ringbuffer (free %d of %d)!",
                       xRingbufferGetCurFreeSize(g_dap_usb_config.parent->dap_dataIN_handle), DAP_BUFFER_SIZE);
        abort();
    }
    // 通知DAP任务处理数据
    xTaskNotifyGive(g_dap_usb_config.parent->kDAPTaskHandle);

    //读数据，在usb配置成功后 `eub_vendord_start`
    usbd_ep_start_read(0, DAP_OUT_EP, g_dap_usb_config.dap_buf, DAP_HANDLE_SIZE);
}

/**
 * @brief DAP输入端点回调函数（设备到主机的数据传输完成时调用）
 * @param busid 总线ID（未使用）
 * @param ep 端点号
 * @param nbytes 传输的字节数
 * 
 * 处理发送给主机的DAP响应：
 * 1. 如果响应缓冲区有待发送数据，启动下一次写入
 * 2. 否则设置空闲标志
 */
void dap_in_callback(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    (void)busid; // 未使用参数
    //通知上一个usb数据发送完成
    vTaskNotifyGiveFromISR(g_dap_usb_config.DapUsbSendTaskHandle, NULL);
}

void usbd_cdc_acm_bulk_out(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    (void)busid;
    if (nbytes == 0) //去除零包
        return;
    xRingbufferSendFromISR(g_dap_usb_config.usb2uart_RB_handle, g_dap_usb_config.uart_buf, nbytes, NULL);
    xEventGroupSetBitsFromISR(g_dap_usb_config.usb_uart_event, USB_UART_USB2UART_EVENT, NULL);
    usbd_ep_start_read(0, CDC_OUT_EP, g_dap_usb_config.uart_buf, DAP_PACKET_SIZE);
}
/**
 * @brief CDC ACM 类批量IN端点传输完成回调函数
 * @param busid USB总线标识符（未使用）
 * @param ep 端点地址（此处应为CDC_IN_EP）
 * @param nbytes 实际传输的字节数
 *
 * 功能说明：
 * 1. 处理USB CDC ACM类批量IN端点（设备->主机方向）的传输完成事件
 * 2. 管理UART接收数据的环形缓冲区（g_uartrx）
 * 3. 实现自动零长度包（ZLP）发送机制
 */
void usbd_cdc_acm_bulk_in(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    (void)busid; // 显式忽略未使用的参数
    // 如果传输的数据长度是最大包大小的整数倍且不为零，发送零长度包
    if ((nbytes % DAP_PACKET_SIZE) == 0 && nbytes) {
        usbd_ep_start_write(0,CDC_IN_EP, NULL, 0);
    }
    // 通知cdc_acm_send_thread任务usb数据发送完成
    //vTaskNotifyGiveFromISR(g_dap_usb_config.cdc_acm_TaskHandle, NULL);
    //ESP_EARLY_LOGE(TAG, "usbd_cdc_acm_bulk_in %d", nbytes);
    // uint32_t size;   // 本次准备发送的数据大小
    // uint8_t *buffer; // 数据缓冲区指针

    // /* 完成上一次线性读取（更新环形缓冲区读指针） */
    // chry_ringbuffer_linear_read_done(&g_uartrx, nbytes);

    // /* 检查是否需要发送零长度包（ZLP） */
    // if ((nbytes % DAP_PACKET_SIZE) == 0 && nbytes) {
    //     /*
    //      * 当传输的字节数是数据包大小的整数倍时（且非零），
    //      * 表示需要发送零长度包（ZLP）通知主机传输结束
    //      */
    //     usbd_ep_start_write(0, CDC_IN_EP, NULL, 0);
    // } else {
    //     /* 检查环形缓冲区是否有待发送数据 */
    //     if (chry_ringbuffer_get_used(&g_uartrx)) {
    //         /*
    //          * 设置新的线性读取区域：
    //          * - buffer: 获取可读数据起始地址
    //          * - size: 获取连续可读数据长度
    //          */
    //         buffer = chry_ringbuffer_linear_read_setup(&g_uartrx, &size);

    //         /* 启动新的USB传输 */
    //         usbd_ep_start_write(0, CDC_IN_EP, buffer, size);
    //     } else {
    //         /* 缓冲区无数据，设置空闲标志 */
    //         usbtx_idle_flag = 1;
    //     }
    // }
}
void swo_in_callback(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    //vTaskNotifyGiveFromISR(swo_task_handle, NULL);
    ESP_EARLY_LOGE(TAG, "swo_in_callback %d", nbytes);
}
struct usbd_endpoint dap_out_ep = {
    .ep_addr = DAP_OUT_EP,
    .ep_cb = dap_out_callback
};

struct usbd_endpoint dap_in_ep = {
    .ep_addr = DAP_IN_EP,
    .ep_cb = dap_in_callback
};
struct usbd_endpoint swo_in_ep = {
    .ep_addr = SWO_IN_EP,
    .ep_cb = swo_in_callback
};
struct usbd_endpoint cdc_out_ep = {
    .ep_addr = CDC_OUT_EP,
    .ep_cb = usbd_cdc_acm_bulk_out
};

struct usbd_endpoint cdc_in_ep = {
    .ep_addr = CDC_IN_EP,
    .ep_cb = usbd_cdc_acm_bulk_in
};

struct usbd_interface dap_intf;
struct usbd_interface intf1;
struct usbd_interface intf2;
struct usbd_interface intf3;
struct usbd_interface hid_intf;

// USB 描述符配置结构体
const struct usb_descriptor cmsisdap_descriptor = {
    // 设备描述符回调函数（获取设备的基本信息，如VID、PID、设备类等）
    .device_descriptor_callback = device_descriptor_callback,
    // 配置描述符回调函数（定义USB设备的配置、接口、端点等）
    .config_descriptor_callback = config_descriptor_callback,
    // 设备品质描述符回调函数（可选，用于返回设备品质描述符）
    .device_quality_descriptor_callback = device_quality_descriptor_callback,
    // 其他速率配置描述符回调函数（用于USB高速/全速/低速兼容性描述）
    .other_speed_descriptor_callback = other_speed_config_descriptor_callback,
    // 字符串描述符回调函数（返回厂商、产品、序列号等字符串信息）
    .string_descriptor_callback = string_descriptor_callback,
    // BOS（Binary Device Object Store）描述符（用于USB 2.1+，支持扩展能力描述）
    .bos_descriptor = &bos_desc,
    // Microsoft OS 2.0描述符（用于Windows兼容性，如自动加载驱动）
    .msosv2_descriptor = &msosv2_desc,
};
void dap_usb_send_thread(void *arg);
void cdc_acm_send_thread(void *arg);
struct usbd_interface *usbd_cdc_acm_init_intf(uint8_t busid, struct usbd_interface *intf);
void dap_usb_init(uint8_t busid, uint32_t reg_base)
{
    /*          启动dap线程          */
    g_dap_usb_config.parent = DAP_Pubilc_Init();

    DAP_Setup();

    usbd_desc_register(0, &cmsisdap_descriptor);

    /*!< winusb */
    usbd_add_interface(0, &dap_intf);
    usbd_add_endpoint(0, &dap_out_ep);
    usbd_add_endpoint(0, &dap_in_ep);
#if (SWO_UART == 1)
    usbd_add_endpoint(0, &swo_in_ep);
#endif/*SWO_UART*/
    /*!< cdc acm */
    usbd_add_interface(0, usbd_cdc_acm_init_intf(0, &intf1));
    usbd_add_interface(0, usbd_cdc_acm_init_intf(0, &intf2));
    usbd_add_endpoint(0, &cdc_out_ep);
    usbd_add_endpoint(0, &cdc_in_ep);

#ifdef CONFIG_CHERRYDAP_USE_MSC
    usbd_add_interface(0, usbd_msc_init_intf(0, &intf3, MSC_OUT_EP, MSC_IN_EP));
#endif

    extern void usbd_event_handler(uint8_t busid, uint8_t event);
    usbd_initialize(busid, reg_base, usbd_event_handler);

    // DAP handle task
    xTaskCreatePinnedToCore(dap_usb_send_thread, "dap_usb_send_thread", 2048, NULL, 10, &g_dap_usb_config.DapUsbSendTaskHandle,
                            DAP_USB_SEND_TASK_AFFINITY);

    // 创建输入环形缓冲区
    g_dap_usb_config.usb2uart_RB_handle = xRingbufferCreate(USB_UART_RB_SIZE, RINGBUF_TYPE_BYTEBUF);
    // 创建输出环形缓冲区
    g_dap_usb_config.uart2usb_RB_handle = xRingbufferCreate(USB_UART_RB_SIZE, RINGBUF_TYPE_NOSPLIT);
    //创建uart事件
    g_dap_usb_config.usb_uart_event = xEventGroupCreate();

    uartx_preinit();
    // CDC-ACM handle task
    xTaskCreatePinnedToCore(cdc_acm_send_thread, "cdc_acm_send_thread", 3 * 1024, NULL, 11, &g_dap_usb_config.cdc_acm_TaskHandle, CDC_ACM_TASK_AFFINITY);
    // 通用SWO配置（UART或Manchester模式）
#if ((SWO_UART != 0) || (SWO_MANCHESTER != 0))
    /**初始化SWO*/
    swo_init();
#endif //((SWO_UART != 0) || (SWO_MANCHESTER != 0))
}

void dap_usb_deinit(uint8_t busid)
{
    usbd_deinitialize(busid);
    vRingbufferDelete(g_dap_usb_config.usb2uart_RB_handle);
    vRingbufferDelete(g_dap_usb_config.uart2usb_RB_handle);
    vTaskDelete(g_dap_usb_config.DapUsbSendTaskHandle);
    vTaskDelete(g_dap_usb_config.cdc_acm_TaskHandle);
    vEventGroupDelete(g_dap_usb_config.usb_uart_event);
    /*删到父类的*/
    DAP_Pubilc_Deinit(g_dap_usb_config.parent);
}

/*************************dap发送线程函数 ***********************/

void dap_usb_send_thread(void *arg)
{
    while (1) {
        // 定义DAP数据包指针
        uint8_t *item_buf;
        // 定义数据包大小变量
        size_t packetSize = 0;
        //ESP_LOGI(TAG, "dap_usb_send_thread running... %x", g_dap_usb_config.parent->dap_dataOUT_handle);
        // 从输出环形缓冲区获取数据
        item_buf = (uint8_t *)xRingbufferReceive(g_dap_usb_config.parent->dap_dataOUT_handle, &packetSize,
                                                 portMAX_DELAY);
        // 如果获取到的数据大小等于DAP处理单元大小
        if (packetSize > 0) {
            // 发送响应数据
            usbd_ep_start_write(0, DAP_IN_EP, item_buf, packetSize);

            // 更新响应计数器
            if (xSemaphoreTake(g_dap_usb_config.parent->data_response_mux, portMAX_DELAY) == pdTRUE) {
                // 响应计数器减1
                --dap_respond;
                // 释放数据响应互斥量
                xSemaphoreGive(g_dap_usb_config.parent->data_response_mux);
            }

            // 等待任务通知,等待usb把上一次发送的数据发送完毕
            ulTaskNotifyTake(pdFALSE, portMAX_DELAY);
            // 返还缓冲区
            vRingbufferReturnItem(g_dap_usb_config.parent->dap_dataOUT_handle, (void *)item_buf);

        } else {
            // 输出数据包大小错误，打印错误信息
            ESP_LOGE(TAG, "Wrong packet zero size!\r\n");
        }
    }
}
/*************************CDC-ACM类接发送线程函数 ************************/

void cdc_acm_send_thread(void *arg)
{
    uint32_t ret;
    uint8_t *buf;
    size_t size;
    uint32_t notify_ret;
    //uart2usb_status_t uart2usb_status = UART2USB_IDLE;
    while (1) {
        ret = xEventGroupWaitBits(g_dap_usb_config.usb_uart_event, USB_UART_CONFIG_EVENT | USB_UART_USB2UART_EVENT | USB_UART_UART2USB_EVENT, pdTRUE, pdFALSE, portMAX_DELAY);
        //ESP_LOGE(TAG, "event:%x", ret);
        /*发送配置信息*/
        if (ret & USB_UART_CONFIG_EVENT) {
            dap_usb2uart_uart_config_callback(&g_cdc_lincoding);
        }
        /*                                      USB2UART                                      */
        if (ret & USB_UART_USB2UART_EVENT) {
            buf = xRingbufferReceive(g_dap_usb_config.usb2uart_RB_handle, &size, pdMS_TO_TICKS(10));
            if (buf != NULL) {
                uart_write_bytes(CDC_ACM_UART_NUM, (const char *)buf, size);
                vRingbufferReturnItem(g_dap_usb_config.usb2uart_RB_handle, (void *)buf);
            }
            /*再读一次，防止绕回*/
            buf = xRingbufferReceive(g_dap_usb_config.usb2uart_RB_handle, &size, pdMS_TO_TICKS(10));
            if (buf != NULL) {
                uart_write_bytes(CDC_ACM_UART_NUM, (const char *)buf, size);
                vRingbufferReturnItem(g_dap_usb_config.usb2uart_RB_handle, (void *)buf);
            }
        }
        /*                                      UART2USB                                      */
        // if (ret & USB_UART_UART2USB_EVENT) {
        //     if (buf != NULL) {
        //         ESP_LOGI(TAG, "xRingbufferReceive size:%d", size);
        //         switch (uart2usb_status) {
        //             case UART2USB_IDLE:
        //                 /* code */
        //                 buf = xRingbufferReceive(g_dap_usb_config.uart2usb_RB_handle, &size, pdMS_TO_TICKS(10));
        //                 // 开始通过 USB 端点发送数据
        //                 //size不定内部发送空,会再从buf取
        //                 usbd_ep_start_write(0, CDC_IN_EP, buf, size);
        //                 uart2usb_status=UART2USB_SEND;
        //                  break;
        //             case UART2USB_SEND:
        //                 /* code */

        //                 // 等待任务通知
        //                 ret = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(3000));
        //                 if(ret)
        //                 {
        //                     uart2usb_status = UART2USB_DONE;
        //                 }
        //                 //ESP_LOGI(TAG, "cdc_acm_send_thread wait ret:%d", ret);
        //                 break;
        //             case UART2USB_DONE:

        //                 //!可能有bug,还没发送完，但buf足够大，应该不会被覆盖
        //                 vRingbufferReturnItem(g_dap_usb_config.uart2usb_RB_handle, (void *)buf);
        //                 ESP_LOGI(TAG, "call vRingbufferReturnItem ");
        //                 uart2usb_status = UART2USB_IDLE;
        //                 /* code */
        //                 break;

        //             default:
        //                 break;
        //         }

        //     }
        // }
        /*                                      UART2USB                                      */
        if (ret & USB_UART_UART2USB_EVENT) {
            //ESP_LOGI(TAG, "USB_UART_UART2USB_EVENT");
            buf = xRingbufferReceive(g_dap_usb_config.uart2usb_RB_handle, &size, pdMS_TO_TICKS(10));
            if (buf != NULL) {
                //ESP_LOGI(TAG, "xRingbufferReceive size:%d", size);
                //打印出数据
                //  for(int i=0;i<size;i++)
                //  {
                //      ESP_LOGI(TAG, "buf[%d]=%x",i,buf[i]);
                //  }
                // 启动USB发送
                //ESP_LOGE(TAG, "usbd_ep_start_write buf addr:%x", buf);
                ret = usbd_ep_start_write(0, CDC_IN_EP, buf, size);
                //ESP_LOGE(TAG, "usbd_ep_start_write ret:%d", ret);
                // 等待发送完成通知（超时3秒）
                //notify_ret = ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(3000)); // pdTRUE：自动清除通知
                //vTaskDelay(pdMS_TO_TICKS(10));
                // if (notify_ret == 0) {
                //     // 超时：发送未完成，记录错误
                //     ESP_LOGE(TAG, "USB send timeout! size:%d", size);
                //     // 可选：重试发送或标记错误
                // }
                // else {
                //     // 发送成功
                //    // ESP_LOGI(TAG, "usbd_cdc_acm_bulk_in %d", size);
                // }

                // 确保无论成功/失败，都归还缓冲区（但需注意：超时情况下缓冲区数据可能已被覆盖）
                vRingbufferReturnItem(g_dap_usb_config.uart2usb_RB_handle, (void *)buf);
                //ESP_LOGI(TAG, "call vRingbufferReturnItem ");
            }
            // buf = xRingbufferReceive(g_dap_usb_config.uart2usb_RB_handle, &size, pdMS_TO_TICKS(10));
            // if (buf != NULL) {
            //     usbd_ep_start_write(0, CDC_IN_EP, buf, size);
            //     // 确保无论成功/失败，都归还缓冲区（但需注意：超时情况下缓冲区数据可能已被覆盖）
            //     vRingbufferReturnItem(g_dap_usb_config.uart2usb_RB_handle, (void *)buf);
            // }
        }
    }
}

/*************************CDC-ACM类接口函数 ***********************/

void usbd_cdc_acm_set_line_coding(uint8_t busid, uint8_t intf, struct cdc_line_coding *line_coding)
{
    (void)busid;
    work_status_t work_status = get_work_status(); // 获取当前工作模式
    work_status = get_work_status();               // 获取当前工作模式
    if (work_status == DAP_WORK)
    {
            if (memcmp(line_coding, (uint8_t *)&g_cdc_lincoding, sizeof(struct cdc_line_coding)) != 0) {
                memcpy((uint8_t *)&g_cdc_lincoding, line_coding, sizeof(struct cdc_line_coding));

                //
                xEventGroupSetBits(g_dap_usb_config.usb_uart_event, USB_UART_CONFIG_EVENT);
            }
    }

}

void usbd_cdc_acm_get_line_coding(uint8_t busid, uint8_t intf, struct cdc_line_coding *line_coding)
{
    (void)busid;
    // work_status_t work_status = get_work_status(); // 获取当前工作模式
    // work_status = get_work_status();               // 获取当前工作模式
    // if (work_status == DAP_WORK) {
        memcpy(line_coding, (uint8_t *)&g_cdc_lincoding, sizeof(struct cdc_line_coding));
    //}
}